package com.xinyue.mqsystem.event;

import com.google.protobuf.GeneratedMessageV3;
import com.google.protobuf.InvalidProtocolBufferException;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.Unpooled;
/**
 * MQ 事件系统交互的消息抽象类
 * @author   wang guang shuai
 * @Company  心悦网络
 * @Date     2020年3月19日 下午2:26:21
 */
public abstract class AbstractEventMessage implements IEventMessage{

    private EventMessageHeader header;
    private String name;

    public AbstractEventMessage() {
        GameEventMetadata gameEventMetadata = this.getClass().getAnnotation(GameEventMetadata.class);
        if(gameEventMetadata != null) {
            this.name = gameEventMetadata.eventName();
            int eventId = gameEventMetadata.eventId();
            header = new EventMessageHeader();
            header.setEventId(eventId);
        } else {
        	throw new IllegalArgumentException("事件对象没有添加事件元数据信息：" + this.getClass().getName());
        }
    }
    @Override
    public EventMessageHeader getHeader() {
        return header;
    }

    @Override
    public String toString() {
        return "AbstractEventMessage [header=" + header + ", name=" + name + "]";
    }
    @Override
    public byte[] write() {
        GeneratedMessageV3.Builder<?> builder = this.getMessageBuilder();
        ByteBuf headerBuf = header.write();
        CompositeByteBuf compositeBuf = Unpooled.compositeBuffer();
        compositeBuf.addComponent(true,headerBuf);
        if(builder != null) {
            byte[] body = builder.build().toByteArray();
            ByteBuf bodyBuf = Unpooled.wrappedBuffer(body);
            compositeBuf.addComponent(true,bodyBuf);
        }
        byte[] value = new byte[compositeBuf.readableBytes()];
        compositeBuf.readBytes(value);
        return value;
    }
    @Override
    public void read(ByteBuf byteBuf) throws InvalidProtocolBufferException {
        header.read(byteBuf);
        if(byteBuf.isReadable()) {
            byte[] body = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(body);
            this.parseFrom(body);
        }
    }
    public abstract GeneratedMessageV3.Builder<?> getMessageBuilder();

    protected abstract void parseFrom(byte[] bytes) throws InvalidProtocolBufferException ;
    
}
